`
https://leetcode.cn/problems/reverse-nodes-in-k-group/
`

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function (head, k) {
  if (head == null) return null;
  // 区间 [a, b) 包含 k 个待反转元素
  let a = head, b = head;
  for (let i = 0; i < k; i++) {
    // 不足 k 个，不需要反转了
    if (b == null) return head;
    b = b.next;
  }
  // 反转前 k 个元素
  let newHead = reverseN(a, k);
  // 此时 b 指向下一组待反转的头结点
  // 递归反转后续链表并连接起来
  a.next = reverseKGroup(b, k);

  return newHead;
};

// 反转前 N 个节点的函数
function reverseN(head, n) {
  if (head == null || head.next == null) {
    return head;
  }
  let pre = null; cur = head; nxt = head.next;
  while (n--) {
    cur.next = pre;
    pre = cur;
    cur = nxt;
    if (nxt != null) {
      nxt = nxt.next;
    }
  }
  head.next = cur;

  return pre;
}